package com.wisezone.net.ex04_server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * socket服务端程序
 * 1. 实例化ServerSocket
 * 2. 监听端口
 *
 *  实现双向收发消息
 */
public class SocketServers {
    private static final int PORT = 9527;
    private Socket socket;

    /**
     * 读消息
     *
     */
    public String readMessage() {
        String line = null;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            line = br.readLine();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return line;
    }

    /**
     * 启动socket服务端程序
     * 实例ServerSocket 监听socket
     */
    public SocketServers() {
        try {
            System.out.println("启动socket服务端...");
            ServerSocket serverSocket = new ServerSocket(PORT); //创建ServerSocket实例
            socket = serverSocket.accept(); //监听端口
            System.out.println("socket连接建立");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 一直接收消息
     */
    public void receiveMesage() {
        while (true) {
            String message = readMessage();
            if (message != null) {
                System.out.println("客户端 :"+message);
            }
        }
    }

    /**
     * 发送消息
     */
    public void sendMessage(String message){
        try {
            PrintWriter sendPw = new PrintWriter(socket.getOutputStream());
            sendPw.println(message);
            sendPw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 从键盘读信息
     */
    public String readMessageByKeyBoard() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = "";
        try {
//            System.out.println("服务端: ");
            line = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return line;
    }

    /**
     * 从键盘读信息发送
     */
    public void sendMessage() {
        while (true) {
            String message = readMessageByKeyBoard();
            sendMessage(message);
        }
    }

    /**
     * 关闭socket
     */
    public void close() {
        try {
            if (socket != null)
                socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
